package org.automated.realestatemanager.db.util;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * 
 * @author A.Pereverziev
 */
public class HibernateUtility {
	private static final Logger log = Logger.getLogger(HibernateUtility.class);
	private static Session session = null;
	// private static final ThreadLocal session = new ThreadLocal();
	private static final SessionFactory sessionFactory = new AnnotationConfiguration()
			.configure().buildSessionFactory();

	protected HibernateUtility() {
	}

	public static Session getSession() {
		// Session session = (Session) DAO.session.get();
		if (session == null) {
			session = sessionFactory.openSession();
			log.info("Hibernate session created " + session.toString());
		}
		return session;
	}

	public static void begin() {
		getSession().beginTransaction();
	}

	public static void commit() {
		getSession().getTransaction().commit();
	}

	public static void rollback() {
		try {
			getSession().getTransaction().rollback();
		} catch (HibernateException e) {
			log.warn("Cannot rollback", e);
		}
		try {
			getSession().close();
		} catch (HibernateException e) {
			log.warn("Cannot close", e);
		}
		HibernateUtility.session = null;
	}

	public static void close() {
		getSession().close();
		HibernateUtility.session = null;
	}

}